package com.example.dllo.keepdemo.train;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.dllo.keepdemo.greendao.TrainWorkouts;
import com.example.dllo.keepdemo.greendao.TrainWorkoutsDao;
import com.example.dllo.keepdemo.greendao.TraniPlan;
import com.example.dllo.keepdemo.greendao.TraniPlanDao;
import com.example.dllo.keepdemo.main.MainActivity;
import com.example.dllo.keepdemo.R;
import com.example.dllo.keepdemo.base.BaseFragment;
import com.example.dllo.keepdemo.tools.DaoSingleton;
import com.example.dllo.keepdemo.tools.GsonRequest;
import com.example.dllo.keepdemo.tools.MetaballView;
import com.example.dllo.keepdemo.tools.MyListView;
import com.example.dllo.keepdemo.tools.VolleySingleton;
import com.example.dllo.keepdemo.train.activity.TrainCourseActivity;
import com.example.dllo.keepdemo.train.activity.TrainPlanActivity;
import com.example.dllo.keepdemo.train.activity.TrainWorkoutsActivity;
import com.example.dllo.keepdemo.train.adapter.PlanListViewAdapter;
import com.example.dllo.keepdemo.train.adapter.WorkoutsListViewAdapter;
import com.example.dllo.keepdemo.train.bean.TrainFragmentBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;


/**
 * Created by dllo on 16/1/8.
 * 训练
 */
public class TrainFragment extends BaseFragment implements AdapterView.OnItemClickListener {
    private ScrollView scrollView;
    private Toolbar toolbar;
    private MyListView planeListView;
    private MyListView workoutsListView;
    private PlanListViewAdapter planListViewAdapter;
    private WorkoutsListViewAdapter workoutsListViewAdapter;
    private List<TrainFragmentBean.DataEntity.PlansEntity> plansEntityList;
    private List<TrainFragmentBean.DataEntity.WorkoutsEntity> workoutsEntityList;
    private TraniPlanDao traniPlanDao = DaoSingleton.getInstance().getTraniPlanDao();
    private TrainWorkoutsDao trainWorkoutsDao = DaoSingleton.getInstance().getTrainWorkoutsDao();
    private TextView tvPlanTitle,tvWorkTitle;
    private MetaballView metaballView;
    private TrainFragmentBean trainFragmentBean;
    private Boolean isHas = true;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_train, container, false);
        scrollView = (ScrollView) view.findViewById(R.id.scroll_fragment_train);
        toolbar = (Toolbar) view.findViewById(R.id.toolbar_fragment_train);
        planeListView = (MyListView) view.findViewById(R.id.listview_fragment_train_plan);
        workoutsListView = (MyListView) view.findViewById(R.id.listview_fragment_train_workouts);
        tvPlanTitle = (TextView) view.findViewById(R.id.tv_fragment_train_plantitle);
        tvWorkTitle = (TextView) view.findViewById(R.id.tv_fragment_fragment_train_worktitle);
        metaballView = (MetaballView) view.findViewById(R.id.metaballview_fragment_train);

        //mob平台授权
        ShareSDK.initSDK(getActivity());

        //解析数据
        initData();
        Log.d("TrainFragment", "createview");
        return view;
    }


    //解析数据
    private void initData() {
        trainFragmentBean = new TrainFragmentBean();
        plansEntityList = new ArrayList<>();
        workoutsEntityList = new ArrayList<>();
        Log.d("TrainFragment", "init" + isHas);

        String url = "https://api.gotokeep.com/v1.1/home/recommend";
        GsonRequest<TrainFragmentBean> gsonRequest = new GsonRequest<TrainFragmentBean>(url, TrainFragmentBean.class, new Response.Listener<TrainFragmentBean>() {
            @Override
            public void onResponse(TrainFragmentBean response) {
                trainFragmentBean = response;
                plansEntityList = response.getData().getPlans();
                workoutsEntityList = response.getData().getWorkouts();
                planListViewAdapter = new PlanListViewAdapter(getActivity(), response.getData().getPlans(),2);
                workoutsListViewAdapter = new WorkoutsListViewAdapter(getActivity(), response.getData().getWorkouts(),2);
                planeListView.setAdapter(planListViewAdapter);
                workoutsListView.setAdapter(workoutsListViewAdapter);

                if (null != traniPlanDao.queryBuilder().list()) {
                    traniPlanDao.deleteAll();
                    addTrainPlanData(plansEntityList);
                } else {
                    addTrainPlanData(plansEntityList);
                }

                if (null != trainWorkoutsDao.queryBuilder().list()) {
                    trainWorkoutsDao.deleteAll();
                    addTrainWorkoutsData(workoutsEntityList);
                } else {
                    addTrainWorkoutsData(workoutsEntityList);
                }
                tvPlanTitle.setText("训练计划");
                tvWorkTitle.setText("单次训练");
                metaballView.setVisibility(View.GONE);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("TrainFragment", "我是error");
                planListViewAdapter = new PlanListViewAdapter(traniPlanDao.queryBuilder().list(), getActivity(), 1);
                planeListView.setAdapter(planListViewAdapter);
                workoutsListViewAdapter = new WorkoutsListViewAdapter(trainWorkoutsDao.queryBuilder().list(), getActivity(), 1);
                workoutsListView.setAdapter(workoutsListViewAdapter);
                tvPlanTitle.setText("训练计划");
                tvWorkTitle.setText("单次训练");
                metaballView.setVisibility(View.GONE);
            }
        });

        VolleySingleton.getInstance()._addRequest(gsonRequest);
        Log.d("TrainFragment", "initData");


    }
    private void addTrainWorkoutsData(List<TrainFragmentBean.DataEntity.WorkoutsEntity> workoutsEntityList) {
        List<TrainWorkouts> workouts = new ArrayList<>();
        for (int i = 0; i < workoutsEntityList.size(); i++) {
            TrainWorkouts trainWorkouts = new TrainWorkouts();
            trainWorkouts.setTitle(workoutsEntityList.get(i).getName());
            trainWorkouts.setDifficulty(workoutsEntityList.get(i).getDifficulty() + "");
            switch (workoutsEntityList.get(i).getDifficulty()) {
                case 1:
                    trainWorkouts.setFoundations("零基础");
                    break;
                case 2:
                    trainWorkouts.setFoundations("初学");
                    break;
                case 3:
                    trainWorkouts.setFoundations("进阶");
                    break;
                case 4:
                    trainWorkouts.setFoundations("强化");
                    break;
                case 5:
                    trainWorkouts.setFoundations("挑战");
                    break;
            }
            trainWorkouts.setEquipments(workoutsEntityList.get(i).getEquipments().get(0).getName());
            trainWorkouts.setTime(workoutsEntityList.get(i).getDuration() + "");
            String content = "";
            for (int j = 0; j < workoutsEntityList.get(i).getTrainingpoints().size(); j++) {
                content = workoutsEntityList.get(i).getTrainingpoints().get(j).getName() + " ";
            }
            trainWorkouts.setBody(content);
            trainWorkouts.setJoin(workoutsEntityList.get(i).getPioneer() + "");
            workouts.add(trainWorkouts);
        }
        trainWorkoutsDao.insertInTx(workouts);

    }

    private void addTrainPlanData(List<TrainFragmentBean.DataEntity.PlansEntity> trainPlanList) {
        List<TraniPlan> traniPlanList = new ArrayList<>();
        for (int i = 0; i < trainPlanList.size(); i++) {
            TraniPlan traniPlan = new TraniPlan();
            traniPlan.setTitle(trainPlanList.get(i).getName());
            traniPlan.setDifficulty(trainPlanList.get(i).getDifficulty() + "");
            switch (trainPlanList.get(i).getDifficulty()) {
                case 1:
                    traniPlan.setFoundations("零基础");
                    break;
                case 2:
                    traniPlan.setFoundations("初学");
                    break;
                case 3:
                    traniPlan.setFoundations("进阶");
                    break;
                case 4:
                    traniPlan.setFoundations("强化");
                    break;
                case 5:
                    traniPlan.setFoundations("挑战");
                    break;
            }
            traniPlan.setEquipments(trainPlanList.get(i).getEquipments().get(0).getName());
            traniPlan.setTime(trainPlanList.get(i).getDays() + "");
            traniPlan.setBody(trainPlanList.get(i).getTrainingpoints().get(0).getName());
            traniPlan.setJoin(trainPlanList.get(i).getPioneer() + "");
            traniPlan.setUrl(trainPlanList.get(i).getPicture());
            traniPlanList.add(traniPlan);
        }
        traniPlanDao.insertInTx(traniPlanList);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //进入页面让ScrollView滑到顶端
        scrollView.smoothScrollTo(0, 0);
        //去掉滑动的阴影
        scrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        scrollView.setVerticalScrollBarEnabled(false);
        toolbar.setTitle("");
        ((MainActivity) getActivity()).setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.icon_data_center_on);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlatformActionListener listener = new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Log.d("TrainFragment", "12312312312312312312312312312312312312");
                        Log.d("TrainFragment", platform.getDb().getUserId());
                        Log.d("TrainFragment", platform.getDb().getUserName());
                        Log.d("TrainFragment", platform.getDb().getUserIcon());
                        Log.d("TrainFragment", "12312312312312312312312312312312312312");
                        Log.d("TrainFragment", "hashMap:" + hashMap);
                        Toast.makeText(getActivity(), "chenggong", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Toast.makeText(getActivity(), "授权失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        Toast.makeText(getActivity(), "取消授权", Toast.LENGTH_SHORT).show();
                    }
                };

                Platform platform = ShareSDK.getPlatform(getActivity(), QQ.NAME);
                //判断是否已经授权过，如果授权，删除授权信息重新授权
                if (platform.isValid()) {
                    platform.removeAccount();
                }
                platform.setPlatformActionListener(listener);
                platform.showUser(null);
                platform.authorize();
            }
        });

        planeListView.setOnItemClickListener(this);
        workoutsListView.setOnItemClickListener(this);
        setHasOptionsMenu(true);
    }

    //menu
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        getActivity().getMenuInflater().inflate(R.menu.menu_fragment_train, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add_fragment_train:
                Intent intent = new Intent(getActivity(), TrainCourseActivity.class);
                startActivity(intent);
                break;
        }
        return true;
    }

    //planeListView的点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (id == 1) {
            Toast.makeText(getActivity(), "点击训练计划", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), TrainPlanActivity.class);
            intent.putExtra("id",plansEntityList.get(position).get_id());
            startActivity(intent);
            Log.d("TrainFragment", plansEntityList.get(position).get_id());
        } else if (id == 2) {
            Toast.makeText(getActivity(), "点击单次训练", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), TrainWorkoutsActivity.class);
            intent.putExtra("id",workoutsEntityList.get(position).get_id());
            startActivity(intent);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isHas = false;
        Log.d("TrainFragment", "pause" + isHas);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (isHas == false) {
            metaballView.setVisibility(View.GONE);
        }
        Log.d("TrainFragment", "resume" + isHas);

    }

}
